<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\ScrollImageRequest;
use App\Models\V1\ScrollImages;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ScrollImagesController extends Controller
{
    /**
     * 显示图片数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('v1.scroll_images');
    }

    /**
     * 获取图片数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的图片数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');

        // 获取符合查询条件的图片数据
        $data = $this->getScrollImageList($currentPage, $rows);
        if (!$data->isEmpty()) {

            $formatList = array();
            $count = $data->total() > 0 ? $data->total() : 0;
            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $objDepartment = $item->department;
                    $formatItem['id'] = $item['id'];
                    $formatItem['url'] = $item['url'];
                    $formatItem['order'] = $item['order'];
                    $formatItem['is_show'] = $this->formateIsShowData($item['is_show']);
                    $formatItem['redirect_url'] = $objDepartment['redirect_url'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }
                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }
        return $response;
    }

    /**
     * 进入单条图片数据显示界面（适用于查看viewData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        switch ($request->input('view')) {
            case 'addData':
                return view('v1.form.scroll_image_item', $data);
                break;
            case 'editData':
                $currentImage = $this->getScrollImageByCode($request->input('code'));
                $data['itemData'] = $currentImage;
                return view('v1.form.scroll_image_item', $data);
                break;
            default:
                break;
        }
    }

    /**
     * 新增基本信息
     *bail关键字表示只要第一个验证失败后面就不验了，提高效率
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '滚动图片[' . $request->input('code') . '],新增失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['url'] = 'bail|required';
            $rules['order'] = 'bail|required';
            $rules['captcha'] = 'bail|required|captcha';
            $messages['url.required'] = '图片不能为空';
            $messages['order.required'] = '显示顺序不能为空';
            $messages['captcha.required'] = '验证码不能为空';
            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request, $rules, $messages);
            
            if($request['isShow'] == 1){
                ScrollImages::where('is_show', 1)
                        ->update([
                            'is_show' => 0,
                        ]);
            }
            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '滚动图片[' . $request->input('code') . '],新增成功！';
            }
        }

        return $response;
    }


    /**
     * 更新图片基本信息(单元格)
     *
     * @param ScrollImageRequest $request
     * @return array
     */
    public function updateCellData(ScrollImageRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '图片代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateScrollImage($request);

            // 更新图片信息
            $successFlag = $this->handleUpdate($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '图片代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 更新图片基本信息
     *
     * @param ScrollImageRequest $request
     * @return array
     */
    public function updateData(ScrollImageRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '图片代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateScrollImage($request);

            //检测是否包含更改是否在手机端显示
            if((isset($request['isShow']))&&($request['isShow'] == 1)){
                ScrollImages::where('is_show', 1)
                    ->update([
                        'is_show' => 0,
                    ]);
            }
            // 更新图片信息
            $successFlag = $this->handleUpdate($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '图片代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 删除图片基本信息
     *
     * @param ScrollImageRequest $request
     * @return array
     */
    public function deleteData(ScrollImageRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '图片代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateScrollImage($request);

            // 删除图片信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '图片代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除图片基本信息
     *
     * @param ScrollImageRequest $request
     * @return array
     */
    public function deleteBatchData(ScrollImageRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '图片批量删除失败！',
        ];

        if ($request->method() === 'POST') {

            // 删除图片信息
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '图片批量删除成功！';
            }
        }

        return $response;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的图片列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getScrollImageList($page = 1, $rows)
    {
        $data = ScrollImages::orderBy('order', 'asc')->paginate($rows, ['*'], 'page', $page);
        return $data;
    }

    /**
     * 根据图片代码获取对应图片信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getScrollImageByCode($code)
    {
        $staff = ScrollImages::where('id', $code)->first();
        return $staff;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新图片信息验证请求
     *
     * @param Request $request
     */
    private function validateScrollImage(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////


    /**
     * 处理新增信息
     *
     * @param Request $request
     * @return bool
     */
    private function handleAdd(Request $request)
    {
        // 拼装新增数据数组
        $insertData = [
            'url' => $request->input('url'),
            'order' => $request->input('order'),
            'redirect_url' => isset($request['redirect_url']) ? $request->input('redirect_url') : '',
            'is_show' => isset($request['isShow']) ? $request->input('isShow') : 0,
        ];
        $rspObj = ScrollImages::create($insertData);
        return $rspObj;
    }



    /**
     * 处理更新图片信息
     *
     * @param Request $request
     * @param bool $bCell 是否为单元格修改数据
     * @return bool
     */
    private function handleUpdate(Request $request, $bCell)
    {
        $where = $request->input('code');

        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }
        } else { // 表单修改
            // 拼装更新数据数组
            $updateData = [
                'url' => $request->input('url'),
                'order' => $request->input('order'),
                'is_show' => isset($request['isShow']) ? $request->input('isShow') : 0,
                'redirect_url' => isset($request['redirect_url']) ? $request['redirect_url'] : '',
            ];
        }
        $rspObj = ScrollImages::where('id', $where)
            ->update($updateData);
        return $rspObj;
    }

    /**
     * 处理更新图片信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');

        if ($bBatch) { // 批量删除
            $codeList = $request->input('code');
            foreach ($codeList as $code) {
                $rspObj = ScrollImages::where('id', $code)->delete();
            }
        } else { // 单条删除
            $rspObj = ScrollImages::where('id',$where)->delete();
        }
        return $rspObj;
    }

    /**
     * 格式化显示发布信息
     *
     * @param $val
     * @return string
     */
    private function formateIsShowData($val)
    {
        $strFormat = '<span class="layui-bg-gray">否</span>';
        if ($val) {
            $strFormat = '<span class="layui-bg-green">是</span>';
        }
        return $strFormat;
    }
}
